//
// Created by pzw on 24-1-4.
//

#include "./CxxHandler.h"
#include <thread>
#include <unistd.h>
#include <iostream>

#define LOOP 99999999

static int inc = 0;

void testFunc(CxxHandler *pCxxHandler) {
    for (int i = 0; i < LOOP; i++) {
        std::cout << ">>>>>>>> testFunc >>> send msg on thread: " << std::this_thread::get_id()
                  << "<<<<<<<<" << std::endl;
        /* 模拟耗时 */
        sleep(10);
        pCxxHandler->post([](CxxMessage *) -> void {
            inc++;
            std::cout << "testFunc >>> after 10s inc = " << (int) inc
                      << " on thread: " << std::this_thread::get_id() << std::endl;
        });
    }
}

#define TEST_FUNC2 0
#if TEST_FUNC2
void testFunc2(CxxHandler *handler) {
    for (int i = 0; i < LOOP; i++) {
        cout << "testFunc2 >>> send msg, index = " << (int) i
             << " on thread: " << std::this_thread::get_id() << endl;
        /* 模拟耗时 */
        sleep(2);
        CxxMessage *msg = CxxMessage::obtain();
        msg->what = 2;
        handler->sendMessage(msg);
        cout << "testFunc2 >>> wait for next" << endl << endl;
    }
}

class SubHandler final : public CxxHandler {
public:
    SubHandler() : CxxHandler() {
    }

    explicit SubHandler(CxxLooper *looper) : CxxHandler(looper) {
    }

    ~SubHandler() override = default;

    void handleMessage(CxxMessage *msg) override {
        inc++;
        cout << "SubHandler >>> handle msg " << msg->what
             << " inc = " << (int) inc << " on thread:" << std::this_thread::get_id() << endl;
    }
};
#endif

int handler2_main(int argc, char *argv[]) {
    std::cout << "handler2_main >>> main thread id is: " << std::this_thread::get_id() << std::endl;
    CxxLooper *looper = CxxLooper::prepare();
    CxxHandler *pCxxHandler = new CxxHandler(looper);
    std::thread threadTestFunc(&testFunc, pCxxHandler);
#if TEST_FUNC2
    CxxHandler *handler2 = new SubHandler(looper);
    thread t2(testFunc2, handler2);
#endif
    CxxLooper::loop();
    return 0;
}